package io.flutter.plugins;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class RealActivity extends FlutterActivity {
    private static final String CHANNEL = "system_share_wx_muti_img";
    private static final String CHANNEL1 = "sharevideomethod";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        GeneratedPluginRegistrant.registerWith(this);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 直接 new MethodChannel，然后设置一个Callback来处理Flutter端调用
        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                        // 在这个回调里处理从Flutter来的调用
//                        Toast.makeText(RealActivity.this,"call",Toast.LENGTH_LONG).show();
                        if (call.method.equals("sharemutiimg")){

//                            List<String> imgs = call.argument("imgs");
//                            Toast.makeText(RealActivity.this,imgs.get(0),Toast.LENGTH_LONG).show();

                            List<String> imgs = call.argument("imgs");
                            ArrayList<String> imgsArr = new ArrayList<>();
                            imgsArr.addAll(imgs);
//                            Toast.makeText(RealActivity.this,imgs.get(0),Toast.LENGTH_LONG).show();

//                            Toast.makeText(RealActivity.this,"call",Toast.LENGTH_LONG).show();
                            if(imgs!= null&&imgs.size()>0){

                                launchSystemShare(imgsArr);
                            }

                            List<String> videos = call.argument("video");


//                            if (videos!=null&&videos.size()>0){
//                                Toast.makeText(RealActivity.this,"sharevideo",Toast.LENGTH_LONG).show();
//                            List<String> video = call.argument("video");
//                            shareVideo(new File(video.get(0)));
//                            }
                        }

                        else

                            if (call.method.equals("sharethefuckvideo")){

//                            moveTaskToBack(false);
//                            result.success(true);

//                            Toast.makeText(RealActivity.this,"sharevideo",Toast.LENGTH_LONG).show();
                            List<String> video = call.argument("video");
                            shareVideo(new File(video.get(0)));
                        }else if(call.method.equals("sharetotimeline")){

                                List<String> imgs = call.argument("imgs");
                                ArrayList<String> imgsArr = new ArrayList<>();
                                imgsArr.addAll(imgs);
//                            Toast.makeText(RealActivity.this,imgs.get(0),Toast.LENGTH_LONG).show();

//                            Toast.makeText(RealActivity.this,"call",Toast.LENGTH_LONG).show();
                                if(imgs!= null&&imgs.size()>0){


//                                    shareTotimeline(imgsArr);
                                    shareImageToWechat(imgsArr,null,RealActivity.this);
                                }




                            }

                    }
                });
//        new MethodChannel(getFlutterView(), CHANNEL1).setMethodCallHandler(
//                new MethodChannel.MethodCallHandler() {
//                    @Override
//                    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
//                        // 在这个回调里处理从Flutter来的调用
//                        Toast.makeText(RealActivity.this,"call",Toast.LENGTH_LONG).show();
//                        if (call.method.equals("sharevideo")){
//                            Toast.makeText(RealActivity.this,"sharevideo",Toast.LENGTH_LONG).show();
//                            List<String> video = call.argument("video");
//                            shareVideo(new File(video.get(0)));
//                        }
//
//                    }
//                });
    }







    /**
     *
     *
     */
    public void launchSystemShare(ArrayList<String> imagePaths ) {
        ArrayList<Uri> uriList = new ArrayList<>();
        //array为要分享图片的本地地址
        for (int i = 0; i <imagePaths.size() ; i++) {
            //将所有的本地地址转换为Uri并添加至集合
            uriList.add(Uri.parse(imagePaths.get(i)));
            //下面这种方式 我得到了错误的本地路径 导致一直无法调起微信


        }
//        file:///storage/emulated/0/%E9%9B%86%E4%BD%B3%E5%A5%BD%E7%89%A9/1598433365802.jpg
        Intent shareIntent = new Intent();
// 如果打开这行代码注释 分享时直接调起微信列表 否则调起系统分享页面
        shareIntent.setComponent(new ComponentName("com.tencent.mm","com.tencent.mm.ui.tools.ShareImgUI"));
        //打开分享界面的Action
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        //指定分享的类型
        shareIntent.setType("image/*");
        //分享传递的数据
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList);
        //打开分享
        startActivity(shareIntent);
    }

    public void shareTotimeline(ArrayList<String> imagePaths ) {
        ArrayList<Uri> uriList = new ArrayList<>();
        //array为要分享图片的本地地址
        for (int i = 0; i <imagePaths.size() ; i++) {
            //将所有的本地地址转换为Uri并添加至集合
            uriList.add(Uri.parse(imagePaths.get(i)));
            //下面这种方式 我得到了错误的本地路径 导致一直无法调起微信


        }
        Intent shareIntent = new Intent();
// 如果打开这行代码注释 分享时直接调起微信列表 否则调起系统分享页面
//        ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        shareIntent.setComponent(new ComponentName("com.tencent.mm","com.tencent.mm.ui.tools.ShareToTimeLineUI"));
        //打开分享界面的Action
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        //指定分享的类型
        shareIntent.setType("image/*");
        //分享传递的数据
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList);
        //打开分享
        startActivity(shareIntent);
    }

    public void shareVideo(File file ) {

        Intent intent = new Intent(Intent.ACTION_SEND);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            Uri fileUri = FileProvider.getUriForFile(RealActivity.this, "io.flutter.plugins"+ ".fileProvider", file);
//            intent.putExtra(Intent.EXTRA_STREAM, fileUri);
//        } else {
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
//        }


            intent.setType("video/*");

        intent.setComponent(new ComponentName("com.tencent.mm","com.tencent.mm.ui.tools.ShareImgUI"));
        startActivity(intent);
    }


    /**
     * 分享多图片到微信朋友圈
     *
     * @param bmp 分享的图片的Bitmap对象
     */
    public void shareImageToWechat(List<String> image,Bitmap bmp, Context mContext) {
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
        String fileName = "share";
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }

        File currentFile = new File(appDir, fileName);
//        FileOutputStream fos = null;
//        try {
//            fos = new FileOutputStream(currentFile);
//            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//            fos.flush();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (fos != null) {
//                    fos.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        ArrayList<Uri> uris = new ArrayList<>();
//        file:///file%3A/storage/emulated/0/%25E9%259B%2586%25E4%25BD%25B3%25E5%25A5%25BD%25E7%2589%25A9/1598432731312.jpg
        Uri uri = null;
        ApplicationInfo applicationInfo = mContext.getApplicationInfo();
        int targetSDK = applicationInfo.targetSdkVersion;
        for (int i=0;i<image.size();i++){
//            fileName = System.currentTimeMillis() + i+".jpg";

            String[] f = image.get(i).split(File.separator);
            fileName = f[f.length-1];
            try {

//                if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(mContext.getContentResolver(), image.get(i), fileName, null));
//                } else {
//                    uri = Uri.fromFile(new File(image.get(i)));
//                }
                uri = Uri.parse(image.get(i));
                uris.add(uri);
            } catch (Exception ex) {

            }


        }

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        intent.setComponent(comp);
        intent.setType("image/*");
        //        intent.putExtra("Kdescription", content);
        if (getVersionCode(mContext, "com.tencent.mm") < 1380) {
            // 微信7.0以下版本
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        } else {
            // 微信7.0及以上版本
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_STREAM, uri);

        }
        mContext.startActivity(intent);
    }



    private static int getVersionCode(Context context, String packageName) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(packageName, 0);
            int version = info.versionCode;

            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}
